package at.jku.se.fastsell.app;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import at.jku.se.fastsell.rest.RestAccess;

public class CreateAuctionActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_auction);

		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.create_auction, menu);
		return true;
	}

	private static boolean isDateParsable(SimpleDateFormat sdf, String txt) {
		boolean parsable = false;
		try {
			sdf.parse(txt);
			parsable = true;
		} catch (ParseException ex) {
			ex.printStackTrace();
		}
		return parsable;
	}

	private static boolean isIntegerParsable(String txt) {
		boolean parsable = false;
		try {
			Integer.parseInt(txt);
			return true;
		} catch (NumberFormatException ex) {
			ex.printStackTrace();
		}
		return parsable;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		} else if (id == R.id.action_overview) {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		} else if (id == R.id.action_logout) {
			Session.currentUser = null;
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_create_auction, container, false);

			Button b = (Button) rootView.findViewById(R.id.createAuction_btn);
			b.setOnClickListener(new MyClickListener());

			return rootView;
		}
	}

	static class MyClickListener implements View.OnClickListener {

		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			boolean ok;
			View v = view.getRootView();
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
			SimpleDateFormat timeFormat = new SimpleDateFormat("mm:ss");
			EditText durationText = ((EditText) v.findViewById(R.id.createAuction_durationText));
			String duration = durationText.getText().toString();
			EditText priceText = ((EditText) v.findViewById(R.id.createAuction_priceText));
			String price = priceText.getText().toString();
			EditText titleText = ((EditText) v.findViewById(R.id.createAuction_titleText));
			String title = titleText.getText().toString();
			EditText descText = ((EditText) v.findViewById(R.id.createAuction_descriptionText));
			String desc = descText.getText().toString();

			priceText.setError(null);
			titleText.setError(null);
			descText.setError(null);
			durationText.setError(null);

			ok = true;
			if (!isIntegerParsable(price)) {
				priceText.setError("number!");
				ok = false;
			} else if (Integer.parseInt(price) <= 0) {
				priceText.setError("number!");
				ok = false;
			}
			if (title.length() < 3) {
				titleText.setError("too short");
				ok = false;
			}
			if (desc.length() < 3) {
				descText.setError("too short");
				ok = false;
			}
			if (Integer.parseInt(duration) <= 0) {
				durationText.setError("invalid");
				ok = false;
			}

			if (ok) {
				try {
					RestAccess.createAuction(title, desc, Double.parseDouble(price), Integer.parseInt(duration),
							Session.currentUser);
					Intent intent = new Intent(v.getContext(), MainActivity.class);
					v.getContext().startActivity(intent);
				} catch (Exception e) {
					AlertDialog.Builder ad = new AlertDialog.Builder(v.getContext());
					ad.setCancelable(false);
					ad.setMessage("Could not create auction: " + e.toString());
					ad.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// TODO
						}
					});
					ad.create().show();
				}

			}
		}
	}
}
